/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/explicit-function-return-type */
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable prefer-const */
import { shell, BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'

// 默认配置
const defaultConfig = {
  width: 900,
  height: 670,
  title: '测试',
  show: false,
  autoHideMenuBar: true,
  ...(process.platform === 'linux' ? { icon } : {}),
  webPreferences: {
    preload: join(__dirname, '../preload/index.js'),
    sandbox: false
  }
}

class WindowHandle {
  // 窗口列表
  windowList: any[]
  constructor() {
    this.windowList = []
  }
  createWin(options: any = {}) {

    // 合拼参数
    const args = Object.assign({}, defaultConfig, options)
    
    // 判断窗口是否存在
    for (let i in this.windowList) {
      if (this.windowList[i].path === args.path) {
        this.windowList[i].win.focus()
        return
      }
    }
    
    // 创建窗口
    const mainWindow = new BrowserWindow(args)

    // 保存当前窗口信息
    const saveId = {
      id: mainWindow.webContents.id,
      path: args.path,
      win: mainWindow
    }

    // 添加到窗口列表
    this.windowList.push(saveId)

    // 跳转
    const url = args.path ? args.path : ''
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'] + '#' + url)
      // 打开调试
      // mainWindow.webContents.openDevTools();
    } else {
      mainWindow.loadFile(join(__dirname, '../renderer/index.html'), { 
        hash: url
      })
    }

    mainWindow.on('ready-to-show', () => {
      mainWindow.show()
    })

    mainWindow.webContents.setWindowOpenHandler((details) => {
      shell.openExternal(details.url)
      return { action: 'deny' }
    })

    // 关闭窗口移除列表
    mainWindow.on('close', () => {
      const index = this.windowList.findIndex((win) => mainWindow.webContents.id === win.id)
      if (index !== -1) {
        this.windowList.splice(index, 1) // 从列表中移除窗口引用
      }
    })

    return {
      saveId
    }
  }
  // 开启主进程监听
  ipcMainListen() {
    // IPC test
    ipcMain.on('ping', () => console.log('pong'))

    // 打开新窗口
    ipcMain.on('open-window', (_, data: object) => {
      this.createWin(data)
    })

    /**pinia多窗口共享 */
    ipcMain.handle('pinia-store-change', (event, jsonStr: string) => {
      // 遍历window执行
      for (const currentWin of BrowserWindow.getAllWindows()) {
        const webContentsId = currentWin.webContents.id
        if (webContentsId !== event.sender.id && !currentWin.isDestroyed()) {
          currentWin.webContents.send('pinia-store-set', jsonStr)
        }
      }
    })
  }
}

export default WindowHandle
